package com.iussoft.receiveData.schedul;

import com.alibaba.fastjson.JSONObject;
import com.apache.tools.DateUtils;
import com.apache.tools.MD5Utils;
import com.apache.tools.StrUtil;
import com.apache.tools.UUIDUtil;
import com.iussoft.model.DataParams;
import com.iussoft.receiveData.send.ReceiveDataManager;
import com.iussoft.receiveData.send.SendSearchManager;
import com.iussoft.receiveData.send.impl.DepositCertificateManager;
import com.iussoft.tools.LoggerUtil;
import com.iussoft.tools.SpringContextLoader;

/**
 * @description: 接收消息线程(发送服务中kafka功能)
 * @author: Hou Dayu
 * @date: Created in 2020/9/7
 */
public class SendService implements Runnable {

    private JSONObject data;
    private String dataType;//同步或异步(同步为空)

    public SendService(JSONObject data, String dataType){
        this.data = data;
        this.dataType = dataType;
    }
    public SendService(JSONObject data){
        this.data = data;
    }

    @Override
    public void run() {
        DataParams params = new DataParams();
        params.setParams(data);
        if(StrUtil.isNull(data.getString("traceId"))){
            params.setParams("traceId", UUIDUtil.getPrimaryKey());
        }
        try{
            DepositCertificateManager manager = (DepositCertificateManager) SpringContextLoader.getBean("depositCertificateManager");
            String cacheKey = MD5Utils.MD5(data.getString("interfaceCode")+data.getString("sendTime"));
            String rowkey = manager.rollbackStr(cacheKey);
            params.setTraceId(rowkey);
            if(StrUtil.isNull(dataType)) {
                if (!"1".equals(data.getString("ifTest"))) {//档板数据不在存证
                    manager.receiveDataMsg(params);
                }
                ReceiveDataManager rmanager = (ReceiveDataManager) SpringContextLoader.getBean("receiveDataManager");
                rmanager.receiveDataMsg(params);//数据解析
            } else {
                SendSearchManager smanager = (SendSearchManager) SpringContextLoader.getBean("sendSearchManager");
                if("send".equals(dataType)){//同步发送
                    smanager.sendDataMsg(params);
                } else if("syncSend".equals(dataType)){//异步发送
                    smanager.syncSendData(params);
                } else {//异步获取
                    smanager.asyncSendData(params);
                }
            }
        } catch (Exception e){
            LoggerUtil.warnSource("exception = Exception; method = receiveDataMsg; traceId = {}; requestTime = {}; requestIp = {}; sourceMessage = {}; errorMessage = {}; exeSys = send; level = {}",params.getParamsToStr("traceId"), DateUtils.Now.fmt_yyyyMMdd_HHmmss(),params.getParamsToStr("requestUseIp"),data.toJSONString().replaceAll("\n","").replaceAll("\r","").replaceAll(";","；"),e.getMessage(),"ERROR");
            e.printStackTrace();
        }
    }
}
